#!/usr/bin/python
# -*- coding: latin-1 -*-

import web
import sys
#from interrogador import Interrogador
from DTOs import FotoInfo, Equipa, Jogador, Ocorrencia
import json

#web.httpserver.runsimple = web.httpserver.runbasic
render = web.template.render('templates/')

urls = (
   '/interrogador', 'init'
)
app = web.application(urls, globals())

import os
'''
dir_path = os.getcwd()

def loadTemplate(fname = 'templates/index.html'):
   stream = None
   
   fs = open(os.path.join(dir_path,fname), 'r')
   stream= fs.read()
   close(fs)
   return stream'''

def pesquisa_remota(dto):
   import httplib
   c = httplib.HTTPConnection('localhost:8001')
   h = {'Content-Type':'text/plain'}
   print dto.__json__()
   c.request('POST', '/', dto.__json__(), headers=h)
   response = c.getresponse()
   data = response.read()
   c.close()
   return data
   
class init:        
   def GET(self):
      #web.header('Content-Type', 'text/html')
      #return loadTemplate()
      return render.index()

   def POST(self):
      form = web.input()
      x = form["inputFilters"]
      print type(x)
      print '*******************************'
      print '*******************************'
      print '*******************************'
      print '*******************************'
      print '*******************************'
      inputs = eval(x)
      #self.getTeam(i)
      #self.getPlayers(i)
      #self.getEvents(i)
      #self.getBallLocation(i)
      
      self.URLs = []
      #query = Interrogador()
      for i in inputs:
         print i
         z = self.dictToDTO(i)
         #self.printData(z)
         self.URLs.extend(eval(pesquisa_remota(z)))
         
      self.URLs = list(set(self.URLs))
      
      for i in range(len(self.URLs)):
         self.URLs[i] = 'static/' + self.URLs[i]
      
      if self.URLs != None:
         return render.showPhotos(self.URLs)
      else:
         return render.index()
      #return self.URLs
      

   def getTeam(self,form):
      team1 = DTOs.Equipa()
      team1.nome = form["Team1Name"]
      team1.tipo = form["Team1Type"]

      team2 = DTOs.Equipa()
      team2.nome = form["Team2Name"]
      team2.tipo = form["Team2Type"]
      
      self.equipa1 = team1
      self.equipa2 = team2
      
   def getPlayers(self,form):
      playersList = form["hiddenPlayersList"]
      self.jogadores = []
      if playersList != "" :
         playersList = playersList.split("#")
         for player in playersList:
            playerAttr = player.split("-")
            player = DTOs.Jogador()
            player.nome = playerAttr[0]
            player.equipa = playerAttr[1]
            if playerAttr[2] == "L":
               player.eCanhoto = True
            else:
               player.eCanhoto = False
            self.jogadores.append(player)
      
      
   def getEvents(self,form):
      event = DTOs.Ocorrencia()
      event.fazCorte = form["Tackle"] 
      event.fazFalta = form["Fault"] 
      event.bolaParada = form["SetPieces"] 
      event.remate = form["Shooting"] 
      event.local = form["EventPlace"]
      if form["Goal"] == "S":
         event.golo = True
      else:
         event.golo = False
      if form["Celebration"] == "S":
         event.festeja = True
      else:
         event.festeja = False
      
      self.ocorrencia = event

   def getBallLocation(self,form):
      ballLocation = DTOs.FotoInfo()
      ballLocation.bolaEsta = form["BallPlace"]
      
      self.fotoInfo = ballLocation
      
   def printData(self, input):
      #Debug
      print ""
      print ""
      print "Log"
      #Print team info
      print "*************************"
      print "Informacao das equipas"
      print "Nome equipa 1: ", input.equipa1.nome
      print "Tipo equipa 1: ", input.equipa1.tipo
      
      print "Nome equipa 2: ", input.equipa2.nome
      print "Tipo equipa 2: ", input.equipa2.tipo
      
      
      #Print players info
      print "*************************"
      print "Informacao dos jogadores da equipa 1"
      if input.equipa1.jogadores == None:
         input.equipa1.jogadores = []
      
      for player in input.equipa1.jogadores:
      
         print "Nome: ",player.nome
         print "Equipa: ", input.equipa1.nome
         print "E canhoto: ", player.eCanhoto
      
         #Print event info
         print "*************************"
         print "Informacao dos eventos"
         print "Corte ", player.ocorrencias[0].fazCorte
         print "Falta ", player.ocorrencias[0].fazFalta
         print "Bola Parada ", player.ocorrencias[0].bolaParada
         print "Remate ", player.ocorrencias[0].remate
         print "Local ", player.ocorrencias[0].local
         print "Golo ", player.ocorrencias[0].golo
         print "Festejo ", player.ocorrencias[0].festeja
      
      print "Informacao dos jogadores da equipa 2"
      if input.equipa2.jogadores == None:
         input.equipa2.jogadores = []
      
      for player in input.equipa2.jogadores:
      
         print "Nome: ",player.nome
         print "Equipa: ", input.equipa2.nome
         print "E canhoto: ", player.eCanhoto
      
         #Print event info
         print "*************************"
         print "Informacao dos eventos"
         print "Corte ", player.ocorrencias[0].fazCorte
         print "Falta ", player.ocorrencias[0].fazFalta
         print "Bola Parada ", player.ocorrencias[0].bolaParada
         print "Remate ", player.ocorrencias[0].remate
         print "Local ", player.ocorrencias[0].local
         print "Golo ", player.ocorrencias[0].golo
         print "Festejo ", player.ocorrencias[0].festeja
      
      #Print location info
      print "*************************"
      print "Localizacao da bola: ", input.bolaEsta
      print "*************************"
      print ""
      print ""
   
   def dictToDTO(self, dict):
      i = FotoInfo()
      i.equipa1 = Equipa()
      i.equipa1.nome = dict["equipa1"]["nome"]
      i.equipa1.tipo = dict["equipa1"]["tipo"]
      if "jogadores" in dict["equipa1"]:
         for player in dict["equipa1"]["jogadores"]:
            p = Jogador()
            p.nome = player["nome"]
            p.equipa = i.equipa1.nome
            p.eCanhoto = player["eCanhoto"]
            if "ocorrencias" in player:
               for event in player["ocorrencias"]:
                  e = Ocorrencia()
                  e.fazCorte = event["fazCorte"]
                  e.fazFalta = event["fazFalta"]
                  e.bolaParada = event["bolaParada"]
                  e.remate = event["remate"]
                  e.golo = event["golo"]
                  e.local = event["local"]
                  e.festeja = event["festeja"]
                  p.ocorrencias.append(e)
            i.equipa1.jogadores.append(p)
      
      i.equipa2 = Equipa()
      i.equipa2.nome = dict["equipa2"]["nome"]
      i.equipa2.tipo = dict["equipa2"]["tipo"]      
      if "jogadores" in dict["equipa2"]:
         for player in dict["equipa2"]["jogadores"]:
            p = Jogador()
            p.nome = player["nome"]
            p.equipa = i.equipa2.nome
            p.eCanhoto = player["eCanhoto"]
            if "ocorrencias" in player:
               for event in player["ocorrencias"]:
                  e = Ocorrencia()
                  e.fazCorte = event["fazCorte"]
                  e.fazFalta = event["fazFalta"]
                  e.bolaParada = event["bolaParada"]
                  e.remate = event["remate"]
                  e.golo = event["golo"]
                  e.local = event["local"]
                  e.festeja = event["festeja"]
                  p.ocorrencias.append(e)
            i.equipa2.jogadores.append(p)
   
      i.bolaEsta = dict["bolaEsta"]
      
      return i
   
   def simulateModuleCall(self, filters):
      print "simulating..."
      return ["http://www.christianoronaldovideos.com/wp-content/uploads/2010/05/cristiano-ronaldo-portugal-captain.jpg", "http://kicktheballs.files.wordpress.com/2010/03/lionel-messi.jpg"]
      
if __name__ == "__main__":
   app.run()